package com.mrdeer.web.controller.app;

import com.mrdeer.common.JSONResult;
import com.mrdeer.common.entity.app.OrderEntity;
import com.mrdeer.common.entity.bo.PayOrderBO;
import com.mrdeer.security.SecurityUtil;
import com.mrdeer.web.service.app.MiniAppOrderService;
import com.mrdeer.web.service.sys.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.Reader;
import java.math.BigDecimal;
import java.util.HashMap;

/**
 * 订单业务接口
 */
@Slf4j
@RestController
@RequestMapping("/wxorder")
@Api(value = "微信支付订单接口", tags = "微信支付订单业务")
public class MiniAppOrderController {

    @Value("${miniapp.app-id}")
    private String appId;

    @Value("${miniapp.key}")
    private String key;

    @Resource
    private SysUserService userService;

    @Resource
    private MiniAppOrderService orderService;

    @Resource
    private SecurityUtil securityUtil;

//    @Resource
//    private MRDeerWXPayConfig wxPayConfig;

    @PostMapping("/create")
    @ApiOperation("创建平台订单")
    public JSONResult createOrder(@RequestBody OrderEntity orderEntity) {
        orderEntity.setCode(Sid.next());
        return JSONResult.ok(orderService.add(orderEntity));
    }

    @PostMapping("/wxpay")
    @ApiOperation("微信订单支付")
    public JSONResult miniWXPayOrder(@RequestBody PayOrderBO payOrderBO, @RequestHeader HashMap header) {
//        User user = securityUtil.getCurrUser();
//        String token = securityUtil.getToken(user.getUsername(), true);
//        String userId = user.getId();
        String orderId = payOrderBO.getOrderId();
//        QueryWrapper wrapper = new QueryWrapper(user);
//        long count = userService.count(wrapper);
//        if (count == 0) {
//            return JSONResult.errorMsg("用户不存在");
//        }
//        String openId = userService.getOne(wrapper).getOpenId();
        String openId = payOrderBO.getOpenId();

        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setId(orderId);
//        orderEntity.setUserId(userId);
//        wrapper = new QueryWrapper(orderEntity);
//        count = orderService.count(wrapper);
//        if (count == 0) {
//            return JSONResult.errorMsg("该用户不存在订单");
//        }
        //TODO:其他验证
        //获取订单信息,准备向微信平台发出请求，创建支付订单
//        orderEntity = orderService.getOne(wrapper);

        //向微信平台发出请求，创建支付订单,注意支付金额为分
        String amount = payOrderBO.getAmount().multiply(new BigDecimal("100")).intValue() + "";
        orderEntity.setCode(Sid.next());
        try {
//            WXPay wxPay = new WXPay(wxPayConfig);
//            HashMap map = new HashMap();
//            map.put("nonce_str", WXPayUtil.generateNonceStr());     //随机字符串
//            map.put("body", "订单备注");
//            map.put("out_trade_no", orderEntity.getCode());
//            map.put("total_fee", amount);
//            map.put("spbill_create_ip", "127.0.0.1");
//            map.put("notify_url", "https://127.0.0.1/test");
//            map.put("trade_type", "JSAPI");
//            map.put("openid", openId);
//            Map<String, String> result = wxPay.unifiedOrder(map);
//            String prepayId = result.get("prepay_id");
//            log.info("------------------>" + prepayId);
//            if (prepayId != null) {
//                orderEntity.setPrepayId(prepayId);
//                UpdateWrapper updateWrapper = new UpdateWrapper();
//                updateWrapper.eq("id", orderEntity.getId());
//                orderService.update(orderEntity, updateWrapper);
//                //生成数字签名
//                map.clear();
//                map.put("appId", appId);
//                map.put("timeStamp", new Date().getTime() + "");
//                map.put("nonceStr", WXPayUtil.generateNonceStr());
//                map.put("package", "prepay_id=" + prepayId);
//                map.put("signType", "MD5");
//                String paySign = WXPayUtil.generateSignature(map, key);
//                map.put("paySign", paySign);
//                return JSONResult.ok(map);
//            } else {
//                return JSONResult.errorMsg("预付订单创建失败");
//            }
        } catch (Exception e) {
            e.printStackTrace();
            return JSONResult.errorMsg("微信下单失败");
        }
        return JSONResult.errorMsg("微信下单失败");
    }

    @ApiOperation("接收消息通知")
    @RequestMapping("/receiveMessage")
    public void receiveMessage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setCharacterEncoding("utf-8");
        Reader reader = request.getReader();
        BufferedReader buffer = new BufferedReader(reader);
        String line = buffer.readLine();
        StringBuffer temp = new StringBuffer();
        while (line != null) {
            temp.append(line);
            line = buffer.readLine();
        }
        buffer.close();
        reader.close();
        String xml = temp.toString();
//        if (WXPayUtil.isSignatureValid(xml, key)) {
//            Map<String, String> map = WXPayUtil.xmlToMap(temp.toString());
//            String resultCode = map.get("result_code");
//            String returnCode = map.get("return_code");
//            if (resultCode.equals("SUCCESS") && returnCode.equals("SUCCESS")) {
//                String outTradeNo = map.get("out_trade_no");
//                UpdateWrapper wrapper = new UpdateWrapper();
//                wrapper.eq("code", outTradeNo);
//                wrapper.set("status", 2);
//                orderService.update(wrapper);
//                response.setCharacterEncoding("utf-8");
//                response.setContentType("application/xml");
//                Writer writer = response.getWriter();
//                BufferedWriter bufferedWriter = new BufferedWriter(writer);
//                bufferedWriter.write("<xml><return_code><![CDATA[SUCCESS]]></return_code> <return_msg><![CDATA[OK]]></return_msg></xml>");
//                bufferedWriter.close();
//                writer.close();
//            }
//        } else {
//            response.sendError(500, "数字签名异常!!");
//        }
    }
}
